package iec104

import (
	"fmt"
	"net"
)

type IEC104Server struct {
	listener net.Listener
}

// 启动服务端
func (server *IEC104Server) Start(address string) error {
	var err error
	server.listener, err = net.Listen("tcp", address)
	if err != nil {
		return err
	}
	fmt.Printf("IEC 104 Server started on %s\n", address)
	for {
		conn, err := server.listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		go server.handleConnection(conn)
	}
}

// 解析 IEC 104 数据包
func parseIEC104Packet(data []byte) {
	if len(data) < 8 {
		fmt.Println("Data too short to be a valid IEC 104 packet")
		return
	}

	// 提取并打印数据包的各个部分
	startDelimiter := data[0]
	length := int(data[1])<<8 | int(data[2])
	controlField := data[3]
	messageData := data[4:]

	fmt.Printf("Start Delimiter: 0x%x\n", startDelimiter)
	fmt.Printf("Length: %d\n", length)
	fmt.Printf("Control Field: 0x%x\n", controlField)
	fmt.Printf("Message Data: %x\n", messageData)
}

// 处理连接
func (server *IEC104Server) handleConnection(conn net.Conn) {
	defer conn.Close()
	fmt.Println("New client connected:", conn.RemoteAddr())
	for {
		buffer := make([]byte, 1024)
		n, err := conn.Read(buffer)
		if err != nil {
			fmt.Println("Error reading from connection:", err)
			return
		}

		if n > 0 {
			go server.handleRequest(buffer[:n], conn)
		}
	}
}

// 处理请求
func (server *IEC104Server) handleRequest(data []byte, conn net.Conn) {
	// 在这里解析数据并处理
	fmt.Printf("Received data: %x\n", data)
	parseIEC104Packet(data)
	// 示例回应：这里可以根据实际协议的需要构建响应
	response := []byte{0x68, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}
	_, err := conn.Write(response)
	if err != nil {
		fmt.Println("Error writing response:", err)
	}
}

//
//func main() {
//	server := &IEC104Server{}
//	err := server.Start(":2404") // IEC 104 默认端口是 2404
//	if err != nil {
//		fmt.Println("Error starting server:", err)
//	}
//}
